package com.hbsoft.lms.controller;


import com.hb.bean.CallResult;
import com.hb.controller.ABaseController;
import com.hbsoft.common.enumtype.AreaUserRoleEnum;
import com.hbsoft.common.enumtype.QrCodeEnum;
import com.hbsoft.lms.bean.AreaUserBean;
import com.hbsoft.lms.bean.BankBean;
import com.hbsoft.lms.bean.BankBranchBean;
import com.hbsoft.lms.bean.QrCodeBean;
import com.hbsoft.lms.dao.service.AreaUserBeanDaoService;
import com.hbsoft.lms.dao.service.BankBeanDaoService;
import com.hbsoft.lms.dao.service.BankBranchBeanDaoService;
import com.hbsoft.lms.dao.service.QrCodeBeanDaoService;
import com.hbsoft.lms.service.WechatService;
import com.hbsoft.util.CompressFiles;
import com.hbsoft.util.GsonUtil;
import com.hbsoft.util.WechatUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "", produces = "application/json;charset=UTF-8")
public class QrCodeController extends ABaseController {

    @Autowired
    private WechatService wechatService;

    @Autowired
    private BankBeanDaoService bankBeanDaoService;

    @Autowired
    private AreaUserBeanDaoService areaUserBeanDaoService;

    @Autowired
    private BankBranchBeanDaoService bankBranchBeanDaoService;

    @Autowired
    private QrCodeBeanDaoService qrCodeBeanDaoService;

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @RequestMapping("makeBankQrCode")
    public String makeBankQrCode(String bankCode){
        CallResult<QrCodeBean> result = new CallResult<>();
        if(StringUtils.isBlank(bankCode)){
            result.setCode(400);
            result.setMsg("参数有误");
            return GsonUtil.toJson(result);
        }
        try {
            BankBean param = new BankBean();
            param.setCode(bankCode);
            BankBean bankBean = bankBeanDaoService.getByField(param);
            if(bankBean != null){
                CallResult<QrCodeBean> qrResult =  wechatService.makeQrCode(bankCode, QrCodeEnum.QR_CODE_BANK.getCode(),bankBean.getName());
                if(qrResult.isExec()){
                    result.setCode(0);
                    result.setMsg("操作成功");
                    qrResult.getData().setName(bankBean.getName());
                    result.setData(qrResult.getData());
                }else{
                    result.setCode(400);
                    result.setMsg(qrResult.getMsg());
                }
            }else{
                result.setCode(400);
                result.setMsg("参数有误");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return GsonUtil.toJson(result);
    }


    @RequestMapping("makeBankBranchQrCode")
    public String makeBankBranchQrCode(String bankCode){
        CallResult<QrCodeBean> result = new CallResult<>();
        if(StringUtils.isBlank(bankCode)){
            result.setCode(400);
            result.setMsg("参数有误");
            return GsonUtil.toJson(result);
        }
        try {
            BankBranchBean param = new BankBranchBean();
            param.setCode(bankCode);
            BankBranchBean bankBranchBean = bankBranchBeanDaoService.getByField(param);
            if(bankBranchBean != null){
                CallResult<QrCodeBean> qrResult =  wechatService.makeQrCode(bankCode, QrCodeEnum.QR_CODE_BANKBRANCH.getCode(),bankBranchBean.getName());
                if(qrResult.isExec()){
                    result.setCode(0);
                    result.setMsg("操作成功");
                    qrResult.getData().setName(bankBranchBean.getName());
                    result.setData(qrResult.getData());
                }else{
                    result.setCode(400);
                    result.setMsg(qrResult.getMsg());
                }
            }else{
                result.setCode(400);
                result.setMsg("参数有误");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return GsonUtil.toJson(result);
    }

    /*@RequestMapping("downloadQrCode")
    private String downloadQrCode(HttpServletResponse response, String bankCodes) {
        CallResult<String> result = new CallResult<>();
        if (bankCodes == null) {
            result.setCode(0);
            result.setMsg("参数有误");
            return GsonUtil.toJson(result);
        }
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            String[] bankCodeArray = bankCodes.split(",");
            List<File> fileList = new ArrayList<>();
            for (String bankCode : bankCodeArray) {
                QrCodeBean param = new QrCodeBean();
                param.setId(bankCode);
                QrCodeBean qrCodeBean = qrCodeBeanDaoService.getByField(param);
                if (qrCodeBean != null && !StringUtils.isBlank(qrCodeBean.getPath())) {
                    String imgPath = ResourceUtils.getURL("classpath:").getPath() + "/static/" + qrCodeBean.getPath();
                    fileList.add(new File(imgPath));
                } else {
                    if(bankCode.length()>3){
                        BankBranchBean bbParam = new BankBranchBean();
                        bbParam.setBankCode(bankCode);
                        BankBranchBean bankBranchBean = bankBranchBeanDaoService.getByField(bbParam);
                        if (bankBranchBean == null) {
                            result.setCode(0);
                            result.setMsg("参数有误");
                        }else {
                            CallResult<QrCodeBean> qrCodeResult = wechatService.makeQrCode(bankCode, QrCodeEnum.QR_CODE_BANKBRANCH.getCode(), bankBranchBean.getName());
                            if (qrCodeResult.isExec()) {
                                String imgPath = ResourceUtils.getURL("classpath:").getPath() + "/static/" + qrCodeResult.getData().getPath();
                                fileList.add(new File(imgPath));
                            }
                        }
                    }else{
                        BankBean bankParam = new BankBean();
                        bankParam.setBankCode(bankCode);
                        BankBean bankBean = bankBeanDaoService.getByField(bankParam);
                        if(bankBean == null){
                            result.setCode(0);
                            result.setMsg("参数有误");
                        }else{
                            CallResult<QrCodeBean> qrCodeResult = wechatService.makeQrCode(bankCode, QrCodeEnum.QR_CODE_BANK.getCode(), bankBean.getName());
                            if (qrCodeResult.isExec()) {
                                String imgPath = ResourceUtils.getURL("classpath:").getPath() + "/static/" + qrCodeResult.getData().getPath();
                                fileList.add(new File(imgPath));
                            }
                        }
                    }
                }
            }
            if (fileList.size() > 0) {
                String fileName = "qrCode.zip";//被下载文件的名称
                String bankFix = bankCodeArray[0].substring(0, 3);
                String zifFilePath = CompressFiles.zipFile(fileList, ResourceUtils.getURL("classpath:").getPath() + "/static/img/qrCode/" + bankFix + "/qrCode.zip");
                File file = new File(zifFilePath);
                if (file.exists()) {
                    response.setContentType("application/force-download");// 设置强制下载不打开
                    response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
                    byte[] buffer = new byte[1024];
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream outputStream = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        outputStream.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return "下载成功";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "下载失败";
    }*/


    @RequestMapping("downloadQrCode")
    private String downloadQrCode(String bankCodes) {
        CallResult<List<QrCodeBean>> result = new CallResult<>();
        if (bankCodes == null) {
            result.setCode(0);
            result.setMsg("参数有误");
            return GsonUtil.toJson(result);
        }
        try {
            String[] bankCodeArray = bankCodes.split(",");
            List<QrCodeBean> fileList = new ArrayList<>();
            for (String bankCode : bankCodeArray) {
                QrCodeBean param = new QrCodeBean();
                param.setId(bankCode);
                QrCodeBean qrCodeBean = qrCodeBeanDaoService.getByField(param);
                if (qrCodeBean != null && !StringUtils.isBlank(qrCodeBean.getUrl())) {
                    fileList.add(qrCodeBean);
                } else {
                    if(bankCode.length()>3){
                        BankBranchBean bbParam = new BankBranchBean();
                        bbParam.setCode(bankCode);
                        BankBranchBean bankBranchBean = bankBranchBeanDaoService.getByField(bbParam);
                        if (bankBranchBean == null) {
                            result.setCode(0);
                            result.setMsg("参数有误");
                        }else {
                            CallResult<QrCodeBean> qrCodeResult = wechatService.makeQrCode(bankCode, QrCodeEnum.QR_CODE_BANKBRANCH.getCode(), bankBranchBean.getName());
                            if (qrCodeResult.isExec()) {
                                qrCodeResult.getData().setName(bankBranchBean.getName());
                                fileList.add(qrCodeResult.getData());
                            }
                        }
                    }else{
                        BankBean bankParam = new BankBean();
                        bankParam.setCode(bankCode);
                        BankBean bankBean = bankBeanDaoService.getByField(bankParam);
                        if(bankBean == null){
                            result.setCode(0);
                            result.setMsg("参数有误");
                        }else{
                            CallResult<QrCodeBean> qrCodeResult = wechatService.makeQrCode(bankCode, QrCodeEnum.QR_CODE_BANK.getCode(), bankBean.getName());
                            if (qrCodeResult.isExec()) {
                                qrCodeResult.getData().setName(bankBean.getName());
                                fileList.add(qrCodeResult.getData());
                            }
                        }
                    }
                }
            }
            result.setCode(0);
            result.setMsg("操作成功");
            result.setData(fileList);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(400);
            result.setMsg("操作异常");
        }
        return gson.toJson(result);
    }



    @RequestMapping("makeBankQrCodeBatch")
    public String makeBankQrCodeBatch(){
        CallResult<String> result = new CallResult<>();
        try {
            CallResult<AreaUserBean> codeResult = getAreaCodeByLogin(AreaUserRoleEnum.AREA_USER_ROLE_Bank.getCode());
            if(!codeResult.isExec()){
                return GsonUtil.toJson(codeResult);
            }
            BankBranchBean param = new BankBranchBean();
            param.setAreaCode(codeResult.getData().getCode());
            List<BankBranchBean> list = bankBranchBeanDaoService.getAll(param);
            for(BankBranchBean bb: list){
                wechatService.makeQrCode(bb.getBankCode(), QrCodeEnum.QR_CODE_BANKBRANCH.getCode(),bb.getName());
            }
            String path =  ResourceUtils.getURL("classpath:").getPath()+ "/static/img/qrCode/" + codeResult.getData().getBankCode() + "/";
            String zipPath =  path + codeResult.getData().getBankCode() + ".zip";
            logger.info("压缩文件 path：{},zip文件路径：zipPath：{}",path,zipPath);
            CompressFiles.compressAllZip(path,"*",zipPath);
            result.setCode(0);
            result.setMsg("生成成功");
            result.setData(zipPath);
        } catch (Exception e) {
            result.setCode(400);
            result.setMsg("生成失败");
            e.printStackTrace();
        }
        return  GsonUtil.toJson(result);
    }



    public CallResult<AreaUserBean> getAreaCodeByLogin(String roleType) throws Exception{
        CallResult<AreaUserBean> result = new CallResult<>();
        AreaUserBean param = new AreaUserBean();
        param.setRoleType(roleType);
        param.setTel(hb_user.getName());
        AreaUserBean au = areaUserBeanDaoService.getByField(param);
        if(au == null || au.getCode() == null || "".equals(au.getCode())){
            result.setCode(400);
            result.setMsg("权限不足");
            return result;
        }else {
            result.setCode(0);
            result.setMsg("操作成功");
            result.setData(au);
        }
        return result;
    }


    public static void main(String[] args) {
       /* String pathAll = "img/qrCode/463/城关支行1.jpg";
        String path = "";
        String fileName = "";
        if (!pathAll.endsWith(File.separator)) {
            fileName = pathAll.substring(pathAll.lastIndexOf("/")+1,pathAll.length() -1);
            path = pathAll.substring(0,pathAll.lastIndexOf("/"));
        }
        System.out.println(fileName);
        System.out.println(path);*/


       String s = "567890";
        System.out.println(s.substring(0,3));
    }
}
